<template>
  <zz-Dialog
    v-model="dialogVisible"
    :title="'新增国际化配置 - ' + formData.locale"
    align-center
    @ok="handleOk"
    @close="handleClose"
    :loading="loading"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <!-- 命名空间列表 -->
      <div class="namespace-container">
        <div class="namespace-header" v-if="!singleMode">
          <el-button size="small" @click="addNamespace" icon="Plus">
            新增命名空间
          </el-button>
        </div>

        <!-- 命名空间列表 -->
        <div
          v-for="(namespace, nsIndex) in formData.namespaces"
          :key="nsIndex"
          class="namespace-item"
        >
          <el-card class="namespace-card" shadow="never">
            <!-- 命名空间头部 -->
            <template #header>
              <div class="namespace-title">
                <el-input
                  v-model="namespace.name"
                  placeholder="请输入命名空间名称"
                  class="namespace-input"
                  :class="{ 'is-error': !namespace.name && showValidation }"
                />
                <div class="namespace-actions" v-if="!singleMode">
                  <el-button
                    size="small"
                    @click="addKeyValue(nsIndex)"
                    icon="Plus"
                  >
                    添加键值对
                  </el-button>
                  <el-button
                    type="danger"
                    plain
                    size="small"
                    @click="removeNamespace(nsIndex)"
                    v-if="formData.namespaces.length > 1"
                    icon="Delete"
                  >
                    删除命名空间
                  </el-button>
                </div>
              </div>
            </template>

            <!-- 键值对列表 -->
            <div class="key-value-container">
              <div
                v-for="(item, kvIndex) in namespace.keyValues"
                :key="kvIndex"
                class="key-value-item"
              >
                <el-row :gutter="12">
                  <el-col :span="6">
                    <el-input
                      v-model="item.key"
                      placeholder="请输入键名"
                      :class="{ 'is-error': !item.key && showValidation }"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-input
                      v-model="item.value"
                      placeholder="请输入翻译值"
                      :class="{ 'is-error': !item.value && showValidation }"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-input
                      v-model="item.description"
                      placeholder="请输入描述（可选）"
                    />
                  </el-col>
                  <el-col
                    :span="2"
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <el-button
                      type="danger"
                      size="small"
                      plain
                      @click="removeKeyValue(nsIndex, kvIndex)"
                      v-if="namespace.keyValues.length > 1"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-col>
                </el-row>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-form>
  </zz-Dialog>
</template>

<script setup>
import { ref, reactive, watch, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  singleMode: {
    type: Boolean,
    default: false,
  },
});

// Emits
const emit = defineEmits(["update:modelValue", "success"]);

// 响应式数据
const dialogVisible = ref(false);
const loading = ref(false);
const formRef = ref();
const locale = ref("zh-CN"); // 从父组件传入的语言环境
const showValidation = ref(false);

// 表单数据
const formData = reactive({
  locale: "zh-CN",
  status: "1",
  namespaces: [
    {
      name: "",
      keyValues: [
        {
          key: "",
          value: "",
          description: "",
        },
      ],
    },
  ],
});

// 表单验证规则
const rules = {};

// 监听父组件传入的显示状态
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      // 弹窗打开时重置表单
      resetForm();
      // 设置当前语言环境
      formData.locale = locale.value;
    }
  }
);

// 监听弹窗显示状态，同步到父组件
watch(dialogVisible, (val) => {
  emit("update:modelValue", val);
});

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    locale: locale.value,
    status: "1",
    namespaces: [
      {
        name: "",
        keyValues: [
          {
            key: "",
            value: "",
            description: "",
          },
        ],
      },
    ],
  });
  showValidation.value = false;
};

// 添加命名空间
const addNamespace = () => {
  formData.namespaces.push({
    name: "",
    keyValues: [
      {
        key: "",
        value: "",
        description: "",
      },
    ],
  });
};

// 删除命名空间
const removeNamespace = (index) => {
  if (formData.namespaces.length > 1) {
    formData.namespaces.splice(index, 1);
  }
};

// 添加键值对
const addKeyValue = (namespaceIndex) => {
  formData.namespaces[namespaceIndex].keyValues.push({
    key: "",
    value: "",
    description: "",
  });
};

// 删除键值对
const removeKeyValue = (namespaceIndex, keyValueIndex) => {
  const namespace = formData.namespaces[namespaceIndex];
  if (namespace.keyValues.length > 1) {
    namespace.keyValues.splice(keyValueIndex, 1);
  }
};

// 验证表单数据
const validateFormData = () => {
  let isValid = true;
  const errors = [];

  // 检查每个命名空间
  formData.namespaces.forEach((namespace, nsIndex) => {
    if (!namespace.name.trim()) {
      isValid = false;
      errors.push(`第${nsIndex + 1}个命名空间名称不能为空`);
    }

    // 检查每个键值对
    namespace.keyValues.forEach((kv, kvIndex) => {
      if (!kv.key.trim()) {
        isValid = false;
        errors.push(
          `${namespace.name || "第" + (nsIndex + 1) + "个命名空间"}的第${
            kvIndex + 1
          }个键名不能为空`
        );
      }
      if (!kv.value.trim()) {
        isValid = false;
        errors.push(
          `${namespace.name || "第" + (nsIndex + 1) + "个命名空间"}的第${
            kvIndex + 1
          }个翻译值不能为空`
        );
      }
    });
  });

  if (!isValid) {
    showValidation.value = true;
    ElMessage.error(errors[0]);
  }

  return isValid;
};

// 关闭弹窗
const handleClose = () => {
  console.log("close");
  dialogVisible.value = false;
};

const handleOk = async () => {
  await handleSubmit();
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 自定义验证
    if (!validateFormData()) {
      return;
    }

    loading.value = true;

    // 构建提交数据
    const submitData = [];
    formData.namespaces.forEach((namespace) => {
      namespace.keyValues.forEach((kv) => {
        submitData.push({
          locale: formData.locale,
          namespace: namespace.name,
          keyPath: kv.key,
          value: kv.value,
          description: kv.description,
          status: formData.status,
        });
      });
    });

    console.log("提交数据", submitData);
    let res =
      await proxy.$API.internationalManagement.international.saveBatch.post(
        submitData
      );

    if (res.code === "01") {
      ElMessage.success("新增成功");
      emit("success"); // 通知父组件刷新数据
      handleClose();
    } else {
      // todo
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 暴露给父组件的方法和属性
defineExpose({
  locale,
  formData,
});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.namespace-container {
  margin-top: 0px;
}

.namespace-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.namespace-header h4 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.namespace-item {
  margin-bottom: 16px;
}

.namespace-card {
  border: 1px solid var(--el-border-color);
}

.namespace-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.namespace-input {
  flex: 1;
  max-width: 300px;
}

.namespace-actions {
  display: flex;
  gap: 8px;
}

.key-value-container {
  padding: 0;
}

.key-value-item {
  margin-bottom: 12px;
  padding: 12px;
  background-color: var(--el-bg-color-page);
  border-radius: 4px;
}

.key-value-item:last-child {
  margin-bottom: 0;
}

.is-error {
  border-color: var(--el-color-danger) !important;
}

.is-error:focus {
  border-color: var(--el-color-danger) !important;
  box-shadow: 0 0 0 2px var(--el-color-danger-light-8) !important;
}

.delete-button-col {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
